package manual

import (
	"fmt"
	"log"
	"math/rand"
	"net/http"
	"path/filepath"
	"time"
	"wisdom_education_in_kunshan/ocr"

	"github.com/gin-gonic/gin"
)

type manualOCR struct{}

// Code ..
type Code struct {
	Path string
	code chan string
}

// OkForm ...
type OkForm struct {
	Code string `form:"code"`
	Name string `form:"name"`
}

var imgCode map[string]*Code

func init() {
	ocr.DefaultOCR = &manualOCR{}
	imgCode = make(map[string]*Code)
}

// OCR notes...
func (m *manualOCR) OCR(args ...string) (string, bool) {
	nt := time.Now()
	codekey := fmt.Sprintf("%02d%02d%02d%02d%02d%02d%05d", nt.Year(), nt.Month(), nt.Day(), nt.Hour(), nt.Minute(), nt.Second(), (rand.Intn(10000) + 1000))
	imageName := filepath.Base(args[0])
	cd := Code{imageName, make(chan string)}
	imgCode[codekey] = &cd
	log.Println("等待识别验证码", imageName)
	ocrCode := <-cd.code
	delete(imgCode, imageName)
	return ocrCode, true
}

// EnableDebug 开启Debug模式 会输出日志
func (m *manualOCR) EnableDebug(enable bool) {
	if enable {
		gin.SetMode(gin.DebugMode)
	} else {
		gin.SetMode(gin.ReleaseMode)
	}
	go func() {
		log.Println("手动模式开启", "http://127.0.0.1:8585/ocr")
		r := gin.Default()
		r.Static("/code", "./tmp")
		r.LoadHTMLFiles("manualserver/ocr.html")
		r.GET("/ping", func(c *gin.Context) {
			c.JSON(200, gin.H{
				"message": "pong",
			})
		})
		r.GET("/ocr", func(c *gin.Context) {
			c.HTML(http.StatusOK, "ocr.html", gin.H{
				"msg":   "world",
				"codes": imgCode,
			})
		})
		r.POST("ok", func(c *gin.Context) {
			var okc OkForm
			c.ShouldBind(&okc)
			mpCode, ok := imgCode[okc.Name]
			if ok {
				mpCode.code <- okc.Code
				delete(imgCode, okc.Name)
			}
			c.Redirect(http.StatusMovedPermanently, fmt.Sprintf("/ocr?t=%d", (rand.Intn(10000)+1000)))
		})
		r.Run(":8585")
	}()
}
